import { envConfig, isDevelopment, isProduction } from "@/config/env";

// 根据环境变量获取API配置
const getApiConfig = () => {
  console.log("API配置:", {
    envConfig,
    isDevelopment,
    isProduction,
  });

  // 开发环境使用代理
  if (isDevelopment) {
    return {
      baseUrl: envConfig.VITE_API_BASE_URL,
      proxyUrl: envConfig.VITE_API_PROXY_URL,
    };
  }

  // 生产环境直接请求后端
  if (isProduction) {
    return {
      baseUrl: envConfig.VITE_API_BASE_URL,
      proxyUrl: envConfig.VITE_API_PROXY_URL,
    };
  }

  // 默认配置
  return {
    baseUrl: "http://localhost:8081",
    proxyUrl: "/api",
  };
};

const apiConfig = getApiConfig();

// 直接请求后端（需要后端配置CORS）
const BASE_URL = apiConfig.baseUrl;
// 使用代理请求后端（推荐，避免跨域问题）
const PROXY_URL = apiConfig.proxyUrl;

// 获取token
function getToken(): string | null {
  return localStorage.getItem("token");
}

// 处理token过期
function handleTokenExpired() {
  console.log("Token已过期，清除本地token并跳转到登录页");
  localStorage.removeItem("token");
  localStorage.removeItem("userInfo");
  localStorage.removeItem("username");
  // 使用router跳转而不是window.location，避免页面刷新
  if (window.location.pathname !== "/login") {
    window.location.href = "/login";
  }
}

// 检查响应中的认证错误
function checkAuthError(responseData: any): boolean {
  if (!responseData) return false;

  // 检查业务状态码
  if (responseData.code === 2001 || responseData.code === 2004) {
    return true;
  }

  // 检查错误消息
  const message = responseData.message || "";
  if (
    message.includes("token") ||
    message.includes("登录") ||
    message.includes("认证") ||
    message.includes("未授权")
  ) {
    return true;
  }

  return false;
}

// 创建带token的请求头
function createAuthHeaders(): Record<string, string> {
  const token = getToken();
  const headers: Record<string, string> = {
    "Content-Type": "application/json",
    Accept: "application/json",
  };

  if (token) {
    headers["Authorization"] = `Bearer ${token}`;
  }

  return headers;
}

export async function post(path: string, data: any) {
  const res = await fetch(BASE_URL + path, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    credentials: "include", // 允许发送cookies
    mode: "cors", // 明确指定CORS模式
    body: JSON.stringify(data),
  });

  if (!res.ok) {
    throw new Error(`HTTP error! status: ${res.status}`);
  }

  return res.json();
}

// 使用代理的POST请求（推荐）
export async function postProxy(path: string, data: any) {
  const res = await fetch(PROXY_URL + path, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: JSON.stringify(data),
  });

  if (!res.ok) {
    throw new Error(`HTTP error! status: ${res.status}`);
  }

  return res.json();
}

// 带token的POST请求（推荐用于需要认证的接口）
export async function postWithAuth(path: string, data: any) {
  const res = await fetch(PROXY_URL + path, {
    method: "POST",
    headers: createAuthHeaders(),
    body: JSON.stringify(data),
  });

  if (!res.ok) {
    if (res.status === 401) {
      handleTokenExpired();
      throw new Error("Token expired, please login again");
    }
    throw new Error(`HTTP error! status: ${res.status}`);
  }

  const responseData = await res.json();

  // 检查业务状态码，处理token过期等认证问题
  if (checkAuthError(responseData)) {
    handleTokenExpired();
    throw new Error("Token expired, please login again");
  }

  return responseData;
}

export async function get(path: string) {
  const res = await fetch(BASE_URL + path, {
    method: "GET",
    headers: {
      Accept: "application/json",
    },
    credentials: "include",
    mode: "cors",
  });

  if (!res.ok) {
    throw new Error(`HTTP error! status: ${res.status}`);
  }

  return res.json();
}

// 使用代理的GET请求（推荐）
export async function getProxy(path: string) {
  const res = await fetch(PROXY_URL + path, {
    method: "GET",
    headers: {
      Accept: "application/json",
    },
  });

  if (!res.ok) {
    throw new Error(`HTTP error! status: ${res.status}`);
  }

  return res.json();
}

// 带token的GET请求（推荐用于需要认证的接口）
export async function getWithAuth(path: string) {
  const res = await fetch(PROXY_URL + path, {
    method: "GET",
    headers: createAuthHeaders(),
  });

  if (!res.ok) {
    if (res.status === 401) {
      handleTokenExpired();
      throw new Error("Token expired, please login again");
    }
    throw new Error(`HTTP error! status: ${res.status}`);
  }

  const responseData = await res.json();

  // 检查业务状态码，处理token过期等认证问题
  if (checkAuthError(responseData)) {
    handleTokenExpired();
    throw new Error("Token expired, please login again");
  }

  return responseData;
}

// 带token的PUT请求
export async function putWithAuth(path: string, data: any) {
  const res = await fetch(PROXY_URL + path, {
    method: "PUT",
    headers: createAuthHeaders(),
    body: JSON.stringify(data),
  });

  if (!res.ok) {
    if (res.status === 401) {
      handleTokenExpired();
      throw new Error("Token expired, please login again");
    }
    throw new Error(`HTTP error! status: ${res.status}`);
  }

  const responseData = await res.json();

  // 检查业务状态码，处理token过期等认证问题
  if (checkAuthError(responseData)) {
    handleTokenExpired();
    throw new Error("Token expired, please login again");
  }

  return responseData;
}

// 带token的DELETE请求
export async function deleteWithAuth(path: string) {
  const res = await fetch(PROXY_URL + path, {
    method: "DELETE",
    headers: createAuthHeaders(),
  });

  if (!res.ok) {
    if (res.status === 401) {
      handleTokenExpired();
      throw new Error("Token expired, please login again");
    }
    throw new Error(`HTTP error! status: ${res.status}`);
  }

  const responseData = await res.json();

  // 检查业务状态码，处理token过期等认证问题
  if (checkAuthError(responseData)) {
    handleTokenExpired();
    throw new Error("Token expired, please login again");
  }

  return responseData;
}

// 文件上传专用函数（不设置Content-Type，让浏览器自动处理multipart）
export async function uploadFile(path: string, formData: FormData) {
  const token = getToken();
  const headers: Record<string, string> = {
    Accept: "application/json",
  };

  if (token) {
    headers["Authorization"] = `Bearer ${token}`;
  }

  const res = await fetch(PROXY_URL + path, {
    method: "POST",
    headers,
    body: formData,
  });

  if (!res.ok) {
    if (res.status === 401) {
      handleTokenExpired();
      throw new Error("Token expired, please login again");
    }
    throw new Error(`HTTP error! status: ${res.status}`);
  }

  const responseData = await res.json();

  // 检查业务状态码，处理token过期等认证问题
  if (checkAuthError(responseData)) {
    handleTokenExpired();
    throw new Error("Token expired, please login again");
  }

  return responseData;
}
